package com.haiheng.module_main.mode

import android.annotation.SuppressLint
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.constant.AppConstant
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.db.KVDatabase
import com.haiheng.library_base.db.LayerMap
import com.haiheng.library_base.http.Domain
import com.haiheng.library_base.http.HttpRequest
import com.haiheng.library_base.http.api
import com.haiheng.library_base.http.get
import com.haiheng.library_base.http.postJson
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.db.BookInfoBean
import com.haiheng.library_base.db.KV
import com.haiheng.module_main.bean.req.BookInfoPageRes
import com.haiheng.module_main.bean.req.PageQueryReq
import com.haiheng.module_main.bean.req.Wherejson
import com.haiheng.module_main.bean.res.QueryBookAcsRes
import com.haiheng.module_main.bean.res.QueryBookAcsResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

/**
 *
 * @Des:书籍信息查询
 * @Author: hwz
 * @Date:2023/6/18 0018
 * @Version: 1.0
 */
class BookInfoViewModel : BaseViewModel() {
    var _bookListData = MutableLiveData<List<BookInfoBean>>()
    var _bookInfoByBarcode = MutableLiveData<BookInfoBean>()
    var _failBookInfoByBarcode = MutableLiveData<BookInfoBean>()
    val bookListData: LiveData<List<BookInfoBean>>
        get() = _bookListData
    var layerInfo = MutableLiveData<LayerMap>()
    var showMsg = MutableLiveData<String>()
    var isFinishSearch = MutableLiveData<Boolean>()
    var queryBookAcsRes = MutableLiveData<QueryBookAcsResult>()

    @SuppressLint("SuspiciousIndentation")
    fun queryBookByLocation(barcode: String) {
        api {
            var book = KVDatabase.getDb().bookInfoDao().getBookInfoByBarCode(barcode)
            if (book != null) {
                LogUtils.d("查询本地书籍 :" + book.toString())
                addBook(book)
                queryBookAcsRes.postValue(getHandleAcsBean(book))
            } else {
                LogWriter.e("本地查询条码：${barcode}失败")
            }
        }
    }


    /**
     * 通过ACS查询书籍信息
     *
     * @param barcode 条码号
     */
    fun queryBookByAcs(barcode: String) {

        LogWriter.d("barcode：${barcode}开始查询")
        val barcodeExists = _bookListData.value?.any { it.barCode == barcode }
        if (barcodeExists == true) return
        if (AppConstant.isOpenOfflineMode()) {
            queryBookByLocation(barcode)
            return
        }
        api {
            val request = HttpRequest(API.PATH.QUERY_BOOK_INFO)
                .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                .putQuery("LibraryCode", AppConstant.getLibraryCode())
                .putQuery("Mac", AppConstant.getMachineUuid())
                .putQuery("BookSn", barcode)
            var response = get<QueryBookAcsRes>(request) {}
            if (response != null) {
                LogWriter.d("查询书籍结果：${response.toJson()}")
                if (response.errorCode.equals("0") && response.result != null) {
                    var bookInfo = response.result
                    var b = BookInfoBean()
                    b.barCode = bookInfo.bookSn
                    b.fixedContainerSub?.name = bookInfo.permanentLocation
                    b.bookTitle = bookInfo.bookTitle
                    b.callNumber = bookInfo.callNumber
                    b.bookOnShelfStatus = bookInfo.circulationStatus
                    b.isSelect = true
                    addBook(b)
                    queryBookAcsRes.postValue(response.result)
                    LogUtils.d("查询书籍 :" + response.toJson())
                } else {
                    LogWriter.e("查询书籍失败 :" + response.toJson())
                }
            } else {
                LogWriter.e("queryBook失败 ${response.toJson()}")
            }
        }
    }

    fun getShelName(outValue: String) {
        api {
            var layerMap = KVDatabase.getDb().getLayerMap().queryByOutValue(outValue)
            if (layerMap != null) {
                layerInfo.postValue(layerMap)
            }
        }
    }

    /**
     * 更具层架号查询书籍列表
     *
     * @param currentContainerId
     */
    fun searchBookLisbByCurrentContainerId(currentContainerId: String) {
        api {
            var db = KVDatabase.getDb()
            var layerMap= db.getLayerMap().queryByOutValue(currentContainerId)
            searchBookLisbByCondition("currentContainerSubId", layerMap.id.toString(), 0)
        }
    }

    /**
     * 更具条件离线查询内容
     *
     * @param fieldName
     * @param fieldValue
     * @param conditionalType
     */
    fun searchBookLisbByConditionOfflineMode(fieldName: String, fieldValue: String, conditionalType: Int) {
        api {
            var db = KVDatabase.getDb()
            var list  = db.bookInfoDao().getAllBookInfo()
            if (conditionalType == 0){
                var resultList = db.bookInfoDao().getBookInfoListByCondition(fieldName,fieldValue)
                LogUtils.d("本地精确查询结果fieldName:${fieldName} fieldValue:${fieldValue} resultList:${resultList.size}")
                _bookListData.postValue(resultList)
            }else{
                var resultList = db.bookInfoDao().getBookInfoListByLikeCondition(fieldName,fieldValue)
                LogUtils.d("本地模糊查询结果fieldName:${fieldName} fieldValue:${fieldValue} 结果:${resultList.size}")
                _bookListData.postValue(resultList)
            }
            isFinishSearch.postValue(true)
        }
    }
    /**
     * 根据条码号，作者，isbn,等条件查询书籍信息
     *
     * @param fieldName 条件名称
     * @param fieldValue 值
     * @param conditionalType  //0精确查询，1，模糊查询
     */
    fun searchBookLisbByCondition(fieldName: String, fieldValue: String, conditionalType: Int) {
        if (AppConstant.isOpenOfflineMode()){
            searchBookLisbByConditionOfflineMode(fieldName,fieldValue,conditionalType)
            return
        }
        api {
            var pageQueryReq = PageQueryReq()
            pageQueryReq.page = 1
            pageQueryReq.length = AppConstant.DEFAULD_PAGE_SIZE
            var wherejson = arrayListOf<Wherejson>()
            var orgCodejson = Wherejson()
            orgCodejson.conditionalType = 0 //0精确查询，1，模糊查询
            orgCodejson.fieldName = "OrgCode"
            orgCodejson.fieldValue = AppConstant.getLibraryCode()
            wherejson.add(orgCodejson)
            var conditionjson = Wherejson()
            conditionjson.conditionalType = conditionalType
            conditionjson.fieldName = fieldName
            conditionjson.fieldValue = fieldValue
            wherejson.add(conditionjson)
            pageQueryReq.wherejson = wherejson
            val request = HttpRequest(API.PATH.SEARCH_MORE_INFO)
                .putHeader(Domain.KEY_NAME, Domain.VALUE_DEFUlT)
                .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                .setJsonObjec(pageQueryReq)
            var response = postJson<BookInfoPageRes>(request)
            if (response.isSuccess == true && response.data != null && response.data.size > 0) {
                LogWriter.e("查询${fieldName}:${fieldValue}书籍成功：${response.data.get(0).bookTitle}")
                _bookListData.postValue(response.data)
            } else {
                _bookListData.postValue(listOf())
                LogWriter.w("获取${fieldName}:${fieldValue}书籍信息失败:${response.toJson()}")
            }
            isFinishSearch.postValue(true)
        }
    }

    fun searchBookInfoByBarCodeOfflineMode(barCode: String) {
        api {
            var result= KVDatabase.getDb().bookInfoDao().getBookInfoByBarCode(barCode)
            if (result != null) {
                LogUtils.e("查询本地书籍${barCode}成功：${result.bookTitle}")
                _bookInfoByBarcode.postValue(result)
            } else {
                var failBook = BookInfoBean()
                failBook.barCode = barCode
                _failBookInfoByBarcode.postValue(failBook)
                LogWriter.w("获取${barCode}本地书籍信息失败:${result}")
            }
        }
    }

    /**
     * 根据条码查询对应书籍详情
     *
     * @param barCode
     */
    fun searchBookInfoByBarCode(barCode: String) {
        if (AppConstant.isOpenOfflineMode()) {
            searchBookInfoByBarCodeOfflineMode(barCode)
            return
        }
        api {
            var pageQueryReq = PageQueryReq()
            pageQueryReq.page = 1
            pageQueryReq.length = AppConstant.DEFAULD_PAGE_SIZE
            var wherejson = arrayListOf<Wherejson>()
            var orgCodejson = Wherejson()
            orgCodejson.conditionalType = 0 //0精确查询，1，模糊查询
            orgCodejson.fieldName = "OrgCode"
            orgCodejson.fieldValue = AppConstant.getLibraryCode()
            wherejson.add(orgCodejson)
            var barCodejson = Wherejson()
            barCodejson.conditionalType = 0
            barCodejson.fieldValue = barCode
            barCodejson.fieldName = "barCode"
            wherejson.add(barCodejson)
            pageQueryReq.wherejson = wherejson
            val request = HttpRequest(API.PATH.SEARCH_MORE_INFO)
                .putHeader(Domain.KEY_NAME, Domain.VALUE_DEFUlT)
                .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                .setJsonObjec(pageQueryReq)
            var response = postJson<BookInfoPageRes>(request)
            if (response.isSuccess == true && response.data != null && response.data.size > 0) {
                LogWriter.e("查询书籍${barCode}成功：${response.data.get(0).bookTitle}")
                _bookInfoByBarcode.postValue(response.data.get(0))
            } else {
                var failBook = BookInfoBean()
                failBook.barCode = barCode
                _failBookInfoByBarcode.postValue(failBook)
                LogWriter.w("获取${barCode}书籍信息失败:${response.toJson()}")
            }
        }
    }

    /**
     * 添加书籍到当前列表
     *
     * @param book
     * @return
     */
    suspend fun addBook(book: BookInfoBean): Boolean = suspendCoroutine { continuation ->
        viewModelScope.launch(Dispatchers.Main) {
            if (_bookListData.value == null) {
                _bookListData.value = listOf(book)
            } else {
                val list = _bookListData.value?.toMutableList()
                book.isSelect = true
                list?.add(book)
                _bookListData.postValue(list!!)
            }
            continuation.resume(true) // 恢复协程，并传递执行结果
        }
    }

    fun getHandleAcsBean(b: BookInfoBean): QueryBookAcsResult {
        var bookAcs = QueryBookAcsResult()
        bookAcs.bookTitle = b.bookTitle
        bookAcs.bookSn = b.barCode
        bookAcs.callNumber = b.callNumber
        bookAcs.isbn = b.isbn
        bookAcs.publisher = b.publisher
        return bookAcs
    }

}